import { RouteRecordRaw } from "vue-router";

// 根据权限路由得到路由信息
export const filterMenus = (
  routes: RouteRecordRaw[],
  parentPath: string = ""
) => {
  const _menus: any = [];
  routes.forEach((item: any) => {
    if (!item.meta.hidden) {
      const _path =
        item.meta && item.meta.url && item.meta.url !== ""
          ? item.meta.url
          : item.path;
      const menu: any = {
        url: generateUrl(_path, parentPath),
        title: item.meta.title,
        icon: item.meta && item.meta.icon ? item.meta.icon : "",
        count: 0,
      };

      if (item.children && item.children.length > 0) {
        const _itemList = item.children.filter((child: any) => !child.hidden);
        if (_itemList.length === 1) {
          menu.title = item.children[0].meta.title;
          menu.url = generateUrl(item.children[0].path, menu.url);
        }
        if (_itemList.length > 1) {
          menu.children = filterMenus(item.children, menu.url);
        }
      }
      _menus.push(menu);
    }
  });
  return _menus;
};

// 根据权限配置得到路由数据
export const filterRoutes = (routes: RouteRecordRaw[], rights: Rights[]) => {
  const _filterRoutes: RouteRecordRaw[] = [];
  rights.forEach((item: Rights) => {
    const target = routes.find((route: any) => route.meta.role === item.value);
    if (target) {
      const { children: childrenRoutes, ...rest } = target;
      const route: any = { ...rest };
      if (item.url) {
        route.meta.url = item.url;
      }
      if (childrenRoutes && childrenRoutes.length > 0) {
        route.children = filterRoutes(childrenRoutes, rights);
      }
      route.meta.title = item.name;
      _filterRoutes.push(route);
    }
  });
  return _filterRoutes;
};
// 路由拼接
const generateUrl = (path: string, parentPath: string) => {
  return path.startsWith("/")
    ? path
    : path
    ? `${parentPath}/${path}`
    : parentPath;
};
